package com.yaorange.medical.parser.breath.factory;

import com.yaorange.medical.parser.api.factory.DeviceDataParseFactory;
import com.yaorange.medical.parser.api.parser.DeviceDataParser;
import com.yaorange.medical.parser.api.parser.WifiDataParser;
import com.yaorange.medical.vo.ParsedBreathRealVo;
import com.yaorange.medical.vo.WifiVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.yaorange.medical.parser.breath.constants.BreathDeviceConstants.*;

/**
 * @author coach tam
 * @email 327395128@qq.com
 * @values 坚持灵活 灵活坚持
 * @since 2024/6/12
 */
@Slf4j
@Component("breathDataParseFactory")
public class BreathDataParseFactory implements DeviceDataParseFactory<ParsedBreathRealVo> {

    @Resource
    private BeanFactory beanFactory;

    @Resource(name = "defaultWifiDataParser")
    private WifiDataParser<WifiVo> wifiDataParser;

    @Override
    public ParsedBreathRealVo parseData(String data) {
        ParsedBreathRealVo parsedBreathRealVo;
        try {
            //1.解析wifi数据
            WifiVo wifiVo = wifiDataParser.parseWifiData(data);

            //2.获取设备类型
            String deviceType = wifiVo.getDeviceType();

            //3.从spring工厂中根据名字自动获取对应设备的解析器
            DeviceDataParser<ParsedBreathRealVo> deviceDataParser = beanFactory.getBean(DeviceDataParser.class, deviceType);

            if (ObjectUtils.isEmpty(deviceDataParser)) {
                throw new IllegalArgumentException("deviceType is not supported");
            }
            //4.开始解析数据
            parsedBreathRealVo = deviceDataParser.parseData(data, wifiVo);
        } catch (Exception e) {
            log.error("解析呼吸机实时数据失败", e);
            throw new RuntimeException(e);
        }
        return parsedBreathRealVo;
    }
}
